/**
 * @Title: index.js
 * @Description: index
 * @author: Fanchao
 * @date: 2020/9/20 7:54 下午
 * @version V1.0
 */

import React, { useImperativeHandle, useState } from 'react';
import BraftEditor from 'braft-editor';
import 'braft-editor/dist/index.css';
import styles from './index.less';
import { Upload, message, Spin } from 'antd';
import { ContentUtils } from 'braft-utils';
import axios from 'axios';
import PictureOutlined from '@ant-design/icons/lib/icons/PictureOutlined';

const controls = [
    'undo', 'redo', 'separator',
    'font-size', 'line-height', 'letter-spacing', 'separator',
    'text-color', 'bold', 'italic', 'underline', 'strike-through', 'separator',
    'superscript', 'subscript', 'remove-styles', 'emoji', 'separator', 'text-indent', 'text-align', 'separator',
    'headings', 'list-ul', 'list-ol', 'blockquote', 'code', 'separator',
    'link', 'separator', 'hr', 'separator',
    // 'media',
    'separator',
    'clear',
];
/**
 *
 * @param template 详情回显
 * @param refRich 为父组件提供方法
 * @returns {*}
 * @constructor
 */
const RichText = ({ template, refRich }) => {
    const [editorState, setEditorState] = useState(() => {
        return BraftEditor.createEditorState(template) || BraftEditor.createEditorState(null);
    });
    const [loading, setLoading] = useState(false);

    const handleEditorChange = (editorState) => {
        setEditorState(editorState);
    };

    const uploadHandler = (param) => {
        if (!param.file) {
            return false;
        }
        const file = param.file;
        const { size, name } = file;
        const isLt2M = size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.info('请上传小于2MB的内容');
            return;
        }
        setLoading(true);
        const formData = new FormData();
        formData.append('file', file);
        axios.post('/user/upload', formData, {}).then((res) => {
            if (res.data.status === 1) {
                message.success(`上传${name}成功`);
                setLoading(false);
                const currentEditorState = ContentUtils.insertMedias(editorState, [{
                    type: 'IMAGE',
                    url: res.data.data[0].url,
                }]);
                setEditorState(currentEditorState);
            }
            setLoading(false);
        }).catch(err => {
            setLoading(false);
        });
    };

    useImperativeHandle(refRich, () => ({
        cbRichHtml: () => {
            return editorState.toHTML();
        },
    }));

    const extendControls = [
        {
            key: 'antd-uploader',
            type: 'component',
            component: (
                <Upload
                    accept="image/*"
                    showUploadList={false}
                    customRequest={uploadHandler}
                >
                    {/* 这里的按钮最好加上type="button"，以避免在表单容器中触发表单提交，用Antd的Button组件则无需如此 */}
                    <button type="button" className="control-item button upload-button" data-title="插入图片">
                        <PictureOutlined/>
                    </button>
                </Upload>
            ),
        },
    ];

    return (
        <>
            <Spin tip="正在上传" spinning={loading}>
                <BraftEditor
                    value={editorState}
                    onChange={handleEditorChange}
                    className={styles.myEditor}
                    controls={controls}
                    extendControls={extendControls}
                />
            </Spin>
        </>
    );
};

export default RichText;
